﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using FineUI;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.Models.BaseInfo;
using ZHDJ.Data.Models.Org;

namespace ZHDJ.WebPage
{
    public class ControlBusiness
    {
        #region 实体上下文

        public static AppBoxContext DB
        {
            get
            {
                if (!HttpContext.Current.Items.Contains("__AppBoxContext"))
                {
                    HttpContext.Current.Items["__AppBoxContext"] = new AppBoxContext();
                }
                return HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
            }
        }

        #endregion

        #region 绑定 

        /// <summary>
        /// 下拉框绑定DataSet
        /// </summary>
        /// <param name="ddl">控件</param>
        /// <param name="ds">数据源</param>
        /// <param name="textField">绑定的文本</param>
        /// <param name="valueField">绑定的值</param>
        /// <param name="isAddDefault">是否加默认值</param>
        public static void ControlBind(DropDownList ddl, DataSet ds, string textField, string valueField, bool isAddDefault = false)
        {
            ddl.DataSource = ds.Tables[0];
            ddl.DataTextField = textField;
            ddl.DataValueField = valueField;

            ddl.DataBind();
            if (isAddDefault)
            {
                ddl.Items.Insert(0, new ListItem() { Text = "==请选择==", Value = "" });
                ddl.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 下拉框绑定IQueryable
        /// </summary>
        /// <param name="ddl">控件</param>
        /// <param name="Query">数据源</param>
        /// <param name="textField">绑定的文本</param>
        /// <param name="valueField">绑定的值</param>
        public static void ControlBind(DropDownList ddl, IQueryable Query, string textField, string valueField, bool isAddDefault = false)
        {
            ddl.DataSource = Query;
            ddl.DataTextField = textField;
            ddl.DataValueField = valueField;

            ddl.DataBind();
            if (isAddDefault)
            {
                ddl.Items.Insert(0, new ListItem() { Text = "==请选择==", Value = "" });
            }
        }
        /// <summary>
        /// 下拉框绑定IQueryable
        /// </summary>
        /// <param name="ddl">控件</param>
        /// <param name="Query">数据源</param>
        /// <param name="textField">绑定的文本</param>
        /// <param name="valueField">绑定的值</param>
        public static void ControlBindEx<T>(System.Web.UI.WebControls.DropDownList ddl, List<T> Query, string textField, string valueField, bool isAddDefault = false) where T : EntityBase
        {
            ddl.DataSource = Query;
            ddl.DataTextField = textField;
            ddl.DataValueField = valueField;

            ddl.DataBind();
            if (isAddDefault)
            {
                ddl.Items.Insert(0, new System.Web.UI.WebControls.ListItem() { Text = "==请选择==", Value = "" });
            }
        }
        /// <summary>
        /// 下拉框绑定数据字典
        /// </summary>
        /// <param name="ddl">控件</param>
        /// <param name="dicType">字典类型</param>
        public static void ControlBindDataDictionary(DropDownList ddl, string dicType, bool isAddDefault = false, string defaultValue = "")
        {
            IQueryable<DataDictionary> q = DB.DataDictionarys;
            q = q.Where(a => a.DDicType == dicType).OrderBy(a => a.OrderNo);
            if (defaultValue != "")
                q = q.Where(a => a.DDicMember == defaultValue);
            ddl.DataSource = q;
            ddl.DataTextField = "DDicMemberName";
            ddl.DataValueField = "DDicMember";

            ddl.DataBind();
            if (isAddDefault)
            {
                ddl.Items.Insert(0, new ListItem() { Text = "==请选择==", Value = "" });
            }
        }

        /// <summary>
        /// 单选框列表绑定DataSet
        /// </summary>
        /// <param name="rbl">控件</param>
        /// <param name="ds">数据源</param>
        /// <param name="textField">绑定的文本</param>
        /// <param name="valueField">绑定的值</param>
        public static void ControlBind(RadioButtonList rbl, DataSet ds, string textField, string valueField)
        {
            rbl.DataSource = ds.Tables[0];
            rbl.DataTextField = textField;
            rbl.DataValueField = valueField;
            rbl.DataBind();
        }

        /// <summary>
        /// 单选框列表绑定IQueryable
        /// </summary>
        /// <param name="rbl">控件</param>
        /// <param name="Query">数据源</param>
        /// <param name="textField">绑定的文本</param>
        /// <param name="valueField">绑定的值</param>
        public static void ControlBind(RadioButtonList rbl, IQueryable Query, string textField, string valueField)
        {
            rbl.DataSource = Query;
            rbl.DataTextField = textField;
            rbl.DataValueField = valueField;
            rbl.DataBind();
        }

        /// <summary>
        /// 单选框列表绑定数据字典
        /// </summary>
        /// <param name="rbl"></param>
        /// <param name="dicType"></param>
        public static void ControlBindDataDictionary(RadioButtonList rbl, string dicType)
        {
            IQueryable<DataDictionary> q = DB.DataDictionarys;
            q = q.Where(a => a.DDicType == dicType).OrderBy(a => a.OrderNo);
            rbl.DataSource = q;
            rbl.DataTextField = "DDicMemberName";
            rbl.DataValueField = "DDicMember";
            rbl.DataBind();
        }



        /// <summary>
        /// 下拉框绑定数据字典
        /// </summary>
        /// <param name="ddl">.net下拉框控件</param>
        /// <param name="dicType"></param>
        /// <param name="isAddDefault"></param>
        public static void ControlBindDataDictionary(System.Web.UI.WebControls.DropDownList ddl, string dicType, bool isAddDefault = false)
        {
            IQueryable<DataDictionary> q = DB.DataDictionarys;
            q = q.Where(a => a.DDicType == dicType).OrderBy(a => a.OrderNo);

            ddl.DataTextField = "DDicMemberName";
            ddl.DataValueField = "DDicMember";
            ddl.DataSource = q.ToList();
            ddl.DataBind();

            if (isAddDefault)
            {
                ddl.Items.Insert(0, new System.Web.UI.WebControls.ListItem() { Text = "==请选择==", Value = "" });
            }
        }




        /// <summary>
        /// 复选框绑定DataSet
        /// </summary>
        /// <param name="ddl">控件</param>
        /// <param name="ds">数据源</param>
        /// <param name="textField">绑定的文本</param>
        /// <param name="valueField">绑定的值</param>
        public static void ControlBind(CheckBoxList cbl, DataSet ds, string textField, string valueField)
        {
            cbl.DataSource = ds.Tables[0];
            cbl.DataTextField = textField;
            cbl.DataValueField = valueField;
            cbl.DataBind();

        }

        /// <summary>
        /// 复选框绑定IQueryable
        /// </summary>
        /// <param name="ddl">控件</param>
        /// <param name="Query">数据源</param>
        /// <param name="textField">绑定的文本</param>
        /// <param name="valueField">绑定的值</param>
        public static void ControlBind(CheckBoxList cbl, IQueryable Query, string textField, string valueField)
        {
            cbl.DataSource = Query;
            cbl.DataTextField = textField;
            cbl.DataValueField = valueField;
            cbl.DataBind();

        }

        /// <summary>
        /// 复选框列表绑定数据字典
        /// </summary>
        /// <param name="cbl"></param>
        /// <param name="dicType"></param>
        public static void ControlBindDataDictionary(CheckBoxList cbl, string dicType)
        {
            IQueryable<DataDictionary> q = DB.DataDictionarys;
            q = q.Where(a => a.DDicType == dicType).OrderBy(a => a.OrderNo);
            cbl.DataSource = q;
            cbl.DataTextField = "DDicMemberName";
            cbl.DataValueField = "DDicMember";
            cbl.DataBind();
        }
        #endregion

        #region 查加控件

        private List<Control> ControlList = new List<Control>();
        /// <summary>
        /// 在父控件的所有子控件中查找控件
        /// </summary>
        /// <param name="control">父控件</param>
        /// <param name="controlType">要查找的控件类型</param>
        /// <returns>找到的控件</returns>
        public List<Control> FindControl(Control control, Type controlType)
        {
            if (control != null && control.Controls.Count > 0)
            {
                foreach (Control c in control.Controls)
                {
                    if (c != null && c.GetType() == controlType)
                    {
                        ControlList.Add(c);
                    }
                    else
                    {
                        FindControl(c, controlType);
                    }
                }
            }

            return ControlList;
        }
        #endregion

        #region picker
        /// <summary>
        /// 转为picker文本
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="textFiled"></param>
        /// <param name="valueField"></param>
        /// <param name="pickerValue"></param>
        /// <returns></returns>
        public static string GetPickerText(string tableName, string textFiled, string valueField, string pickerValue)
        {
            var ids = StringHelper.AddQuoteString(pickerValue);
            ids = string.IsNullOrEmpty(ids) ? "''" : ids;
            string commandText = string.Format("SELECT {1} FROM {0} WHERE {2} IN ({3})", tableName, textFiled, valueField, ids);
            var dataSet = MySqlHelper.ExecuteDataSet(commandText);
            return ToPicker(dataSet.Tables[0], textFiled);
        }

        /// <summary>
        /// datatable转为Picker文本或者值 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>
        public static string ToPicker(DataTable dt, string columnName)
        {
            if (dt.Rows.Count == 0)
            {
                return string.Empty;
            }
            var texts = new List<string>();
            foreach (DataRow dataRow in dt.Rows)
            {
                if (dataRow[columnName].ToString() != "")
                {
                    texts.Add(dataRow[columnName].ToString());
                }
            }
            return texts.Count < 1 ? "" : string.Join(",", texts.ToArray());
        }

        /// <summary>
        ///  把ID转为Picker值 
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public static string ToPicker(IQueryable<EntityBase> q)
        {
            if (q == null)
            {
                return "";
            }
            var texts = new List<string>();
            foreach (var item in q)
            {

                texts.Add(item.ID);

            }
            return texts.Count < 1 ? "" : string.Join("','", texts.ToArray());
        }



        /// <summary>
        /// 获取组织Piker文本
        /// </summary>
        /// <param name="pickerValue"></param>
        /// <returns></returns>
        public static string GetBranchPickerText(string pickerValue)
        {
            var ids = StringHelper.AddQuoteString(pickerValue);
            ids = string.IsNullOrEmpty(ids) ? "''" : ids;
            string commandText = string.Format("SELECT BranchName FROM tblPartyOrgBranch WHERE BranchID IN ({0})", ids);
            var dataSet = MySqlHelper.ExecuteDataSet(commandText);
            return ToPicker(dataSet.Tables[0], "BranchName");
        }


        /// <summary>
        /// 获取人员Piker文本
        /// </summary>
        /// <param name="pickerValue"></param>
        /// <returns></returns>
        public static string GetMembersPickerText(string pickerValue)
        {
            var ids = StringHelper.AddQuoteString(pickerValue);
            ids = string.IsNullOrEmpty(ids) ? "''" : ids;
            string commandText = string.Format("SELECT UserName FROM tblPartyOrgMember WHERE LoginID IN ({0})", ids);
            var dataSet = MySqlHelper.ExecuteDataSet(commandText);
            return ToPicker(dataSet.Tables[0], "UserName");
        }
        #endregion

        #region 表格相关

        /// <summary>
        /// 获表格选行中的第一个值
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        public static string GetSelectedDataKeyID(Grid grid)
        {
            string id = "-1";
            int rowIndex = grid.SelectedRowIndex;
            if (rowIndex >= 0)
            {
                id = Convert.ToString(grid.DataKeys[rowIndex][0]);
            }
            return id;
        }

        /// <summary>
        /// 获表格选中行的指定值
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="dataIndex"></param>
        /// <returns></returns>
        public static string GetSelectedDataKey(Grid grid, int dataIndex)
        {
            string data = String.Empty;
            int rowIndex = grid.SelectedRowIndex;
            if (rowIndex >= 0)
            {
                data = grid.DataKeys[rowIndex][dataIndex].ToString();
            }
            return data;
        }

        /// <summary>
        /// 获取表格选中项DataKeys的第一个值，并转化为整型列表
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        public static List<string> GetSelectedDataKeyIDs(Grid grid)
        {
            List<string> ids = new List<string>();
            foreach (int rowIndex in grid.SelectedRowIndexArray)
            {
                ids.Add(Convert.ToString(grid.DataKeys[rowIndex][0]));
            }

            return ids;
        }

        #endregion

        /// <summary>
        /// 设置控件集为只读
        /// </summary>
        /// <param name="cons"></param>
        public static void SetReadOnly(ControlCollection cons)
        {
            foreach (var item in cons)
            {
                var c = item as Field;
                if (c != null)
                    c.Readonly = true;
            }
        }
    }
}
